package com.sparrow.utils;

import java.util.ArrayList;
import java.util.List;

import com.sparrow.constant.CONFIG;
import com.sparrow.constant.PAGER;
import com.sparrow.constant.REGEX;

public class HtmlUtil {

	public static String getDomain() {
		return Config.getValueInCache(CONFIG.ROOT_PATH).substring(
				"http://www.".length());
	}

	/**
	 * 获取分页字符串
	 * 
	 * @author zhanglizhi
	 * @date May 29, 2011
	 * @version 1.0
	 * @param currentPageIndex
	 * @param rowCount
	 * @param pageSize
	 * @param pageFormat
	 * @return
	 */
	public static String getPageString(int currentPageIndex, int recordCount,
			int pageSize, String pageFormat) {
		return getPageString(currentPageIndex, recordCount, pageSize,
				pageFormat, null, false);

	}

	/**
	 * 获取分页字符串
	 * 
	 * @author zhanglizhi
	 * @date May 29, 2011
	 * @version 1.0
	 * @param currentPageIndex
	 * @param rowCount
	 * @param pageSize
	 * @param pageFormat
	 * @param indexPageFormat
	 * @param isSimple
	 * @return
	 */
	public static String getPageString(int currentPageIndex, int rowCount,
			int pageSize, String pageFormat, String indexPageFormat,
			boolean isSimple) {
		int pageSizeOfPage = 5;
		if (rowCount > pageSize) {
			String pageNumberStyle = " class=\"num\"";
			String disablePageNumStyle = "class=\"disable\"";
			StringBuffer pageString = new StringBuffer();
			pageString.append("<div id=\"divPage\" class=\"page\">\n");
			boolean isConvertHTML = pageFormat.endsWith(".html") ? true : false;
			if (!isConvertHTML) {
				pageString
						.append("<input type=\"hidden\" id=\"currentPageIndex\" name=\"currentPageIndex\" value=\""
								+ currentPageIndex + "\"/>\n");
			}
			int pagecount = (int) Math.ceil(rowCount / (float) pageSize);
			if (currentPageIndex != 1) {
				if (StringUtil.isNullOrEmpty(indexPageFormat)) {
					pageString.append("<a " + pageNumberStyle + " href=\""
							+ pageFormat.replace(PAGER.PAGE_INDEX, "1")
							+ "\">首页</a>\n");
				} else {
					pageString.append("<a " + pageNumberStyle + " href=\""
							+ indexPageFormat.replace(PAGER.PAGE_INDEX, "1")
							+ "\">首页</a>\n");
				}
				if (!StringUtil.isNullOrEmpty(indexPageFormat)
						&& currentPageIndex - 1 == 1) {
					pageString.append("<a "
							+ pageNumberStyle
							+ " href=\""
							+ indexPageFormat.replace(PAGER.PAGE_INDEX,
									String.valueOf(currentPageIndex - 1)));
					pageString.append("\">上一页");
					pageString.append("</a>\n");
				} else {
					pageString.append("<a "
							+ pageNumberStyle
							+ " href=\""
							+ pageFormat.replace(PAGER.PAGE_INDEX,
									String.valueOf(currentPageIndex - 1)));
					pageString.append("\">上一页");
					pageString.append("</a>\n");
				}
			} else {
				pageString.append("<a " + disablePageNumStyle + ">首页</a>\n<a "
						+ disablePageNumStyle + ">上一页</a>\n");
			}
			int beginpageindex = currentPageIndex - (pageSizeOfPage - 1);
			if (currentPageIndex % pageSizeOfPage != 0) {
				beginpageindex = currentPageIndex - currentPageIndex
						% pageSizeOfPage + 1;
			}

			int endpageindex = beginpageindex + 4;
			for (int i = beginpageindex; i <= endpageindex; i++) {
				if (i > pagecount) {
					break;
				}
				if (i == currentPageIndex) {
					pageString
							.append("<span style='color:red;font-weight:bold;'>");
					pageString.append(i);
					pageString.append("</span>\n");
				} else if (i == 1 && !StringUtil.isNullOrEmpty(indexPageFormat)) {
					pageString.append("<a " + pageNumberStyle + " href=\""
							+ indexPageFormat.replace(PAGER.PAGE_INDEX, "1")
							+ "\">" + i + "</a>\n");
				} else {
					pageString.append(" <a "
							+ pageNumberStyle
							+ " href=\""
							+ pageFormat.replace(PAGER.PAGE_INDEX,
									String.valueOf(i)) + "\">");
					pageString.append(i);
					pageString.append("</a>\n");
				}
			}

			if (currentPageIndex < pagecount) {
				pageString.append("<a "
						+ pageNumberStyle
						+ " href=\""
						+ pageFormat.replace(PAGER.PAGE_INDEX,
								String.valueOf(currentPageIndex + 1)));
				pageString.append("\">下一页");
				pageString.append("</a>\n");
				pageString.append("<a "
						+ pageNumberStyle
						+ " href=\""
						+ pageFormat.replace(PAGER.PAGE_INDEX,
								String.valueOf(pagecount)) + "\">末页</a>\n");
			} else {
				pageString.append("<a " + disablePageNumStyle + ">下一页</a><a "
						+ disablePageNumStyle + "\">末页</a>\n");
			}
			if (!isSimple) {
				pageString
						.append("<input id=\"defPageIndex\" onmouseover=\"this.select();\" onkeyup=\"this.value=this.value.replace(/\\D/g,'');\"  onafterpaste=\"this.value=this.value.replace(/\\D/g,'');\" style='width:30px;height:20px;' "
								+ "onblur=\"if(this.value.trim()==''){this.value=parseInt($('currentPageIndex').value)+1;}\" value=\""
								+ (currentPageIndex + 1)
								+ "\" type=\"text\" />\n");

				pageString
						.append("<a id=\"go\" onmouseover=\"mouse.over(this);\"  onmouseout=\"mouse.out(this);\" onclick=\"page.toTargetPage("
								+ pagecount
								+ ",'"
								+ pageFormat
								+ "',this);\" style='font-weight:bold'>GO</a>\n");
				pageString.append("	<span style='color:#5f5f60'>\n");
				pageString
						.append("<span style='diplay:none;' id='spanCurrentPageIndex'>\n");
				pageString.append(currentPageIndex);
				pageString.append("</span>共<span>\n");
				pageString.append(pagecount);
				pageString.append("</span>页	每页<span id='rowCountPerPage'>");
				pageString.append(pageSize);
				pageString.append("</span>条	共<span id='sumOfRecord'>");
				pageString.append(rowCount);
				pageString.append("</span>条");
				pageString.append("</span>");
			}

			pageString.append("</div>");
			return pageString.toString();
		} else {
			return "<input type=\"hidden\" id=\"currentPageIndex\" name=\"currentPageIndex\" value=\"1\"/>\n";
		}
	}

	/**
	 * 根据总记录数和每页记录数获取最后页码
	 * 
	 * @author zhanglizhi
	 * @date Jul 16, 2011
	 * @version 1.0
	 * @param recordCount
	 * @param pageSize
	 * @return
	 */
	public static int getLastPageIndex(int recordCount, int pageSize) {
		return (int) Math.ceil((double) recordCount / pageSize);
	}

	public static int getCountWithoutHtml(String sourceHTML) {
		// 过滤多余的回车
		sourceHTML = sourceHTML.replaceAll(REGEX.TAG_BR, "<br/>");
		// 过滤多余的空格
		sourceHTML = sourceHTML.replaceAll(REGEX.TAG_HTML_SPACE, "&nbsp;");
		// 字符数组
		char[] chars = sourceHTML.toCharArray();
		// 字符索引
		int index = 0;
		// 是否标签字符标记
		boolean isHTMLTag = false;
		// 当前字符
		char currentChar;
		int count = 0;
		while (index < chars.length) {
			currentChar = chars[index++];
			// HTML标签开始
			if (currentChar == '<') {
				// 说明以下内容是标签部分
				isHTMLTag = true;
			}
			// 标签部分
			if (isHTMLTag) {
				// HTML标签结束
				if (currentChar == '>') {
					// 当前标签结束
					isHTMLTag = false;
				}
				// 正文部分
			} else {
				// 当前字符不是空
				if (currentChar != '\n' && currentChar != '\r') {
					count++;
				}
			}
		}
		return count;
	}

	public static String filterHTML(String sourceHTML) {
		return filterHTML(sourceHTML, "</p><p>");
	}

	/**
	 * 过滤HTML字符中的html标记
	 * 
	 * 要过滤掉html的转义字符
	 * 
	 * @author zhanglizhi
	 * @date 2011-12-25
	 * @version 1.0
	 * @param sourceHTML
	 * @return
	 */
	public static String filterHTML(String sourceHTML, String splitTag) {
		// 过滤多余的回车
		sourceHTML = sourceHTML.replaceAll(REGEX.TAG_BR, " ");
		// 过滤转义字符
		sourceHTML = sourceHTML.replaceAll(REGEX.TAG_HTML_ESCAPE, "");
		// 字符数组
		char[] chars = sourceHTML.toCharArray();
		// 字符索引
		int index = 0;
		// 是否标签字符标记
		boolean isHTMLTag = false;
		// 目录字符串
		StringBuffer desc = new StringBuffer();
		// 标签名
		StringBuffer tagName = null;
		// 标签队列
		List<String> tagQueue = new ArrayList<String>();
		// 当前字符
		char currentChar;
		// 段落标记
		String p = splitTag;
		while (index < chars.length) {
			currentChar = chars[index++];
			// HTML标签开始
			if (currentChar == '<') {
				// 说明以下内容是标签部分
				isHTMLTag = true;
				// 新标签开始
				tagName = new StringBuffer();
			}
			// 标签部分
			if (isHTMLTag) {
				tagName.append(currentChar);
				// HTML标签结束
				if (currentChar == '>') {
					// 当前标签结束
					isHTMLTag = false;
					// 标签结束后加入标签队列
					tagQueue.add(tagName.toString().trim());
				}
				// 正文部分
			} else {
				// 内容开始 检测标签队列
				if (tagQueue.size() > 0) {
					// 如果多个标签紧接着出现，则只分一段
					for (int i = 0; i < tagQueue.size(); i++) {
						// 是否为块标签
						if (isBlockTag(tagQueue.get(i))) {
							desc.append(p);
							break;
						}
					}
					// 内容开始标签队列清空
					tagQueue.clear();
				}
				// 当前字符不是空
				if (currentChar != '\n' && currentChar != '\r'
						&& currentChar != ' ' && currentChar != '\t') {
					desc.append(currentChar);
				}
			}
		}
		String result = desc.toString().trim();
		result = result.replaceAll("(<p>)+", "<p>");
		result = result.replaceAll("(<\\/p>)+", "</p>");
		result = result.replaceAll("(<p><\\/p>)*", "");
		result = result.replaceAll("(<\\/p><p>)+", "</p><p>");
		if (result.startsWith("</p><p>")) {
			result = result.substring("</p><p>".length());
		}
		if (result.endsWith("</p><p>")) {
			result = result.substring(0, result.length() - "</p><p>".length());
		}
		return result;
	}

	
	/**
	 * 是否块标签
	 * 
	 * @author zhanglizhi
	 * @date 2011-12-28
	 * @version 1.0
	 * @param tagName
	 * @return
	 */
	public static boolean isBlockTag(String tagName) {
		return StringUtil.matches(tagName, REGEX.TAG_BLOCK);
	}
}
